package model;

import model.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

////通过这个类，封装用户表的基本操作
public class UserDao {

    //1.根据userId来查用户信息
    public User selectById(int userId)
    {
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;

        try {
            //1.建立连接
            connection= DbUtil.getConnection();
            //2.构造sql语句
            String sql="select * from user where userId=?";
            statement=connection.prepareStatement(sql);
            statement.setInt(1,userId);
            //3.执行sql语句
            resultSet=statement.executeQuery();

            //4.遍历结果
            if(resultSet.next())
            {
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            DbUtil.close(connection,statement,resultSet);
        }
        return null;
    }

    //2.根据username来查用户信息（登陆的时候）
    public User selectByUaername(String username)
    {
        Connection connection=null;
        PreparedStatement statement=null;
        ResultSet resultSet=null;

        try {
            //1.建立连接
            connection=DbUtil.getConnection();
            //2.构造sql语句
            String sql="select * from user where username=?";
            statement=connection.prepareStatement(sql);
            statement.setString(1,username);
            //3.执行sql语句
            resultSet=statement.executeQuery();

            //4.遍历结果
            if(resultSet.next())
            {
                User user=new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            DbUtil.close(connection,statement,resultSet);
        }
        return null;
    }
}
